package com.dengdai.applibrary.json;

import android.util.Log;

import com.dengdai.applibrary.data.ExtJsonForm;
import com.dengdai.applibrary.utils.LogUtils;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 解析Json数据
 *
 * @author 等待
 * @class ParseJson.java
 * @time 2015年5月15日 上午12:36:03
 * @QQ 2743569843
 */
public class ParseJson {

    public static ExtJsonForm parseJson(String json) {
        ExtJsonForm extJsonForm = null;
        try {
            ExtJsonFormBuilder builder = new ExtJsonFormBuilder();
            extJsonForm = builder.build(new JSONObject(json));
        } catch (Exception e) {
        }
        return extJsonForm;

    }

    /**
     * 解析数组
     *
     * @param json
     * @param c
     * @return
     * @throws Exception
     */
    public static <T> List<T> parseJsonArray(String json, Class<T> c) {
        List<T> objects = new ArrayList<T>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                objects.add(parseClass(jsonArray.getString(i), c));
            }
        } catch (Exception e) {
            Log.i("INFO", e.getMessage());
        }
        return objects;
    }

    /**
     * 解析数组
     *
     * @param json
     * @param c
     * @return
     * @throws Exception
     */
    public static <T> ArrayList<T> parseJsonArrays(String json, Class<T> c) {
        ArrayList<T> objects = new ArrayList<T>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                objects.add(parseClass(jsonArray.getString(i), c));
            }
        } catch (Exception e) {
            Log.i("INFO", e.getMessage());
        }
        return objects;
    }

    /**
     * 把JSON数据转换为对象
     *
     * @param dataJson
     * @param c
     * @return
     * @throws Exception
     */
    public static <T> T parseClass(String dataJson, Class<T> c) {
        T t = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.getDeserializationConfig().set(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            t = objectMapper.readValue(dataJson, c);
        } catch (Exception e) {
            LogUtils.i("=====>" + e.getMessage());
            e.printStackTrace();
        }
        return t;
    }
}
